package net.ib.mtalk.ui.attachment.sound;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AudioRecordActivity extends BaseActivity {

	private AudioRecordManager audioRecordManager = new AudioRecordManager();

	private Button resetButton;
	private Button startButton;
	private Button stopButton;

	protected OnClickListener resetButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			resetAction();
		}
	};

	protected OnClickListener startButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			startAction();
		}
	};

	protected OnClickListener stopButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			stopAction();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initUI();

		resetAction();
	}

	@Override
	protected void onPause() {
		MTalkLogWriter.d(this.getClass()+".onPause() - STT");

		super.onPause();

		cancelAction();

		MTalkLogWriter.d(this.getClass()+".onPause() - STT");
	}

	@Override
	public void onResume() {
		MTalkLogWriter.d(this.getClass()+".onResume() - STT");

		super.onResume();
		resetAction();

		MTalkLogWriter.d(this.getClass()+".onResume() - STT");
	}

	@Override
	public void onDestroy() {
		MTalkLogWriter.d(this.getClass()+".onDestroy() - STT");

		cancelAction();

		super.onDestroy();

		MTalkLogWriter.d(this.getClass()+".onDestroy() - END");
	}

	/**
	 * 변하지 않는 UI 요소들
	 */
	private void initUI() {
		setContentView(R.layout.layout_attachment_record_audio);

		resetButton = (Button) findViewById(R.id.btn_reset_record_audio);
		startButton = (Button) findViewById(R.id.btn_start_record_audio);
		stopButton = (Button) findViewById(R.id.btn_stop_record_audio);

		resetButton.setOnClickListener(resetButtonListener);
		startButton.setOnClickListener(startButtonListener);
		stopButton.setOnClickListener(stopButtonListener);

		resetButton.setClickable(false);
		startButton.setClickable(false);
		stopButton.setClickable(false);
	}

	/**
	 * @return 다음 녹음을 할 때 기록할 파일의 경로.
	 * 리턴 시점에 아직 파일은 만들어지지 않았고 중간 디렉토리는 만들어졌다.
	 */
	private String readyTargetFilePath() {
		try {
			String state = android.os.Environment.getExternalStorageState();
			if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
				throw new IOException("SD Card is not mounted.  It is " + state + ".");
			}
		} catch (IOException e) {
			MTalkLogWriter.e(e);
			return null;
		}

		String path = MTalkConstant.MTALK_PATH + "/audio";
		File directory = new File(path);
		if(!directory.exists()){
			directory.mkdirs();
		}
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				MTalkLogWriter.e(e);
			}
		}
		String dateString = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSSZ").format(new Date());
		path += "/mnTalkAudio_" + dateString + ".mp4";

		return path;
	}

	/**
	 * 결과를 세팅하고 이 액티비티를 종료한다. 이 액티비티의 호출자에게는 결과의 주소가 담긴 인텐트를 반환한다.
	 * @param fileUrl 결과 파일의 주소
	 */
	private void submitResult(String fileUrl) {
		Intent intent = new Intent();
		intent.setData(Uri.parse(fileUrl));
		if (fileUrl == null) {
			setResult(RESULT_CANCELED, intent);
		} else {
			setResult(RESULT_OK, intent);
		}

		finish();
	}

	private void resetAction() {
		try {
			audioRecordManager.resetRecorder(readyTargetFilePath());

			resetButton.setClickable(false);
			startButton.setClickable(true);
			stopButton.setClickable(false);
		} catch(Exception e) {
			MTalkLogWriter.e(e);
			Toast.makeText(AudioRecordActivity.this, "Fail", Toast.LENGTH_SHORT).show();
		}

	}

	private void startAction() {
		try {
			audioRecordManager.startRecorder();

			resetButton.setClickable(true);
			startButton.setClickable(false);
			stopButton.setClickable(true);
		} catch(Exception e) {
			MTalkLogWriter.e(e);
			Toast.makeText(AudioRecordActivity.this, "Fail", Toast.LENGTH_SHORT).show();
		}
	}

	private void stopAction() {
		try {
			submitResult(audioRecordManager.stopRecorder());

			resetButton.setClickable(false);
			startButton.setClickable(false);
			stopButton.setClickable(false);
		} catch(Exception e) {
			MTalkLogWriter.e(e);
			Toast.makeText(AudioRecordActivity.this, "Fail", Toast.LENGTH_SHORT).show();
		}
	}

	private void cancelAction() {
		if (audioRecordManager == null)
			return;

		audioRecordManager.cancelRecorder();
		audioRecordManager = null;
	}


}
